package lookie.app.ui.prefs;

import java.awt.BorderLayout;

import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;

import lookie.app.ui.app.SettingsIds;
import lookie.swing.laf.LookAndFeelDescriptor;
import lookie.swing.laf.LookAndFeelRegistry;

import org.springframework.richclient.list.BeanPropertyValueListRenderer;
import org.springframework.richclient.list.ComboBoxListModel;
import org.springframework.richclient.preference.PreferencePage;

public class LookAndFeelPreferencePage extends PreferencePage {

	private LookAndFeelRegistry lookAndFeelRegistry;

	private JComboBox lookAndFeelComboBox;

	private ComboBoxListModel lookAndFeelComboBoxModel;

	public LookAndFeelPreferencePage() {
		super("lookAndFeelPreferencePage");
	}

	public void setLookAndFeelRegistry(LookAndFeelRegistry lookAndFeelRegistry) {
		this.lookAndFeelRegistry = lookAndFeelRegistry;
	}

	@Override
	protected JComponent createContents() {
		createLookAndFeelComboBox();
		final JLabel lookAndFeelComboBoxLabel = new JLabel("Look And Feel");
		LookAndFeelPreferencePanel panel = new LookAndFeelPreferencePanel(
				new LookAndFeelPreferencePanelParams() {

					public JComboBox getLookAndFeelComboBox() {
						return lookAndFeelComboBox;
					}

					public JLabel getLookAndFeelComboBoxLabel() {
						return lookAndFeelComboBoxLabel;
					}

				});
		JPanel wrapper = getComponentFactory().createPanel(new BorderLayout());
		wrapper.add(panel, BorderLayout.CENTER);
		
		onAboutToShow();
		
		return wrapper;
	}

	private void createLookAndFeelComboBox() {
		createLookAndFeelComboBoxModel();
		lookAndFeelComboBox = new JComboBox(lookAndFeelComboBoxModel);
		lookAndFeelComboBox.setRenderer(new BeanPropertyValueListRenderer(
				"name"));
	}

	private void createLookAndFeelComboBoxModel() {
		lookAndFeelComboBoxModel = new ComboBoxListModel();
		String[] groupIds = lookAndFeelRegistry.getGroupIds();
		for (String groupId : groupIds) {
			for (LookAndFeelDescriptor descriptor : lookAndFeelRegistry
					.getDescriptors(groupId)) {
				lookAndFeelComboBoxModel.add(descriptor);
			}
		}
	}

	@Override
	protected void onDefaults() {
		String id = getSettings().getDefaultString(SettingsIds.LAF);
		LookAndFeelDescriptor descriptor = lookAndFeelRegistry
				.getDescriptor(id);
		lookAndFeelComboBoxModel.setSelectedItem(descriptor);
	}

	@Override
	protected boolean onFinish() {
		LookAndFeelDescriptor selected = (LookAndFeelDescriptor) lookAndFeelComboBoxModel.getSelectedItem();
		getSettings().setString(SettingsIds.LAF, selected.getId());
		return super.onFinish();
	}

	public void onAboutToShow() {
		String currentId = getSettings().getString(SettingsIds.LAF);
		LookAndFeelDescriptor currentDescriptor = lookAndFeelRegistry
				.getDescriptor(currentId);
		lookAndFeelComboBoxModel.setSelectedItem(currentDescriptor);
	}

}
